package com.jy.controller;

import com.jy.common.Base64Image;
import com.jy.common.CSRFTokenManager;
import com.jy.common.SessionInfo;
import com.jy.common.UUIDUtils;
import com.jy.model.*;
import com.jy.service.CopeCreditService;
import com.jy.service.MoneyManageService;
import com.jy.service.UserInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/7/6 0006.
 */
@Controller
@RequestMapping("/ccc")
public class CopeCreditController {
    @Resource
    private CopeCreditService copeCreditService;
    @Autowired
    UserInfoService userInfoService;

    @RequestMapping("/insertCreditApply")
    public @ResponseBody
    boolean insertCreditApply(CopeCredit mm,
                             String pocessId, String dbUser, String id, String type, String dbnames,String CSRFToken,HttpSession session){
        if(CSRFToken == null || !CSRFToken.equals(session.getAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME).toString())){
            return false;
        }else {
            User user = userInfoService.getUserInfo(mm.getToken());
            double rate = Double.parseDouble(mm.getRate()) / 100;
            mm.setRate(String.valueOf(rate));
            mm.setId(UUIDUtils.getUUID());
            mm.setApply_man(user.getId());
            mm.setDids(user.getDid());
		/*if(mm.getYjrepayment_money2()==""){
			mm.setYjrepayment_money2("0");
		}*/
            // 申请流程
            Department dept = new Department();
            Department center = new Department();
            Department pro = new Department();
            if (mm.getDeptId() != null && !mm.getDeptId().equals("")) {
                dept = copeCreditService.searchdept(mm.getDeptId());
            } else {
                dept.setDepartment_name("");
            }
            if (mm.getCenterId() != null && !mm.getCenterId().equals("")) {
                center = copeCreditService.searchdept(mm.getCenterId());
            } else {
                center.setDepartment_name("");
            }
            if (mm.getProjectDeptId() != null && !mm.getProjectDeptId().equals("")) {
                pro = copeCreditService.searchdept(mm.getProjectDeptId());
            } else {
                pro.setDepartment_name("");
            }
            mm.setProject_namegd2(dept.getDepartment_name() + center.getDepartment_name() + pro.getDepartment_name() + mm.getProject_namegd2());
            User users = copeCreditService.user(dbUser);
            mm.setSybcwzj(users.getUsername());

            boolean flag = copeCreditService.insertCopeApply(mm, user.getId(), dbUser, dbnames);
            int a = toimages(mm);
            return flag;

        }

    }

    public Integer toimages(CopeCredit mm){
        String imgs=mm.getImgs();
        String imgnames=mm.getImgsname();
        int a=0;
        if(!"".equals(imgs)&&imgs!=null){
            imgs=mm.getImgs().substring(1);
            imgnames=mm.getImgsname().substring(1);

        String []img=imgs.split("&");
        String []imgname=imgnames.split("&");
        System.out.println("img.length:"+img.length);

        List<CopeFile> list=new ArrayList<CopeFile>();
        for(int i=0;i<img.length;i++){
            String b=img[i].substring(img[i].indexOf(",")+1);
            String c=imgname[i].substring(imgname[i].indexOf(",")+1);
            String filepath= Base64Image.GenerateImage(b,createPath(c));
            CopeFile mf=new CopeFile();
            mf.setFilename(filepath);
            mf.setCopeId(mm.getId());
            mf.setId(UUIDUtils.getUUID());
            list.add(mf);

        }
        a=copeCreditService.saveFilename(list);
        }
        //user.setCard_information(filepath);
        return a;
    }

    public  String createPath(String imagName){
        Properties prop =  new  Properties();
        InputStream ins =LoginController.class.getResourceAsStream("/filepath.properties");
        try {
            prop.load(ins);
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        String savePath=prop.getProperty("filepath");
        File filefolder=new File(savePath);
        if(!filefolder.isDirectory()){
            filefolder.mkdirs();
        }
        String a=imagName.substring(0, imagName.indexOf("."));
        String b=imagName.substring(imagName.indexOf("."));
        long seconds=System.currentTimeMillis();
        String path=savePath+"/"+a+"-"+seconds+b;
        return path;
    }



    /**
     * 查询待审核信息
     *
     */
    @RequestMapping("/getTaskCredit")
    public @ResponseBody List<CopeCredit> getTaskCredit(Integer state,Integer size,String token) {
        List<CopeCredit> list = copeCreditService.getTaskCredit(state,size,token);
        return list;
    }

    /**
     * 查询待审核单个详细信息
     *
     */
    @RequestMapping("/getsingTaskCredit")
    public @ResponseBody
    Map<String,Object> getsingTaskMoney(String id, String processId) {
        System.out.println("processId:"+processId);
        MoneyManage list = copeCreditService.getsingTaskCredit(id);
        List<com.jy.model.Comment> lists=copeCreditService.getCommentInfo(processId);
        List<CopeFile> mfList=copeCreditService.getImgS(id);

/*
		list.setBtns(mmService.getTaskPvm(list.getTaskid()));
*/
        Map<String,Object> map = new HashMap<String,Object>();

        map.put("mm", list);
        map.put("lists", lists);
        map.put("mfList", mfList);
/*
		map.put("list", comments);
*/
        return map;
    }

    /**
     * 请假申请已提交，进行审核
     *
     * @param pocessId
     * @param dbUser
     * @param
     * @return
     */



    @RequestMapping("/applySh")
    public @ResponseBody
    Json applySh(CopeCredit mm, String pocessId, String dbUser,
                 String commons, String id, HttpSession session, String btnName,
                 String name, String apply_money, String dbname, String type,String cl_time) {

        User user=userInfoService.getUserInfo(mm.getToken());
        Map<String, Object> variables = new HashMap<String, Object>();
        // 把指定的审核人插入记录
        String state = null;
		/*try {
			//name = new String(name.getBytes("iso-8859-1"), ("utf-8"));
			//dbname = new String(dbname.getBytes("iso-8859-1"), ("utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
        if(dbname!=null && !dbname.equals("null") && !dbname.equals("")){
            dbname = dbname.substring(0, dbname.indexOf("--"));
        }
        name=copeCreditService.searchName(pocessId);
		/*System.out.println(name+"==name");
		System.out.println(dbname+"==dbname");
		System.out.println(btnName+"==btnName");*/
        mm = new CopeCredit();
        if (name.equals("事业部财务总监审核")) {
            mm.setSybzjl(dbname);
            if (btnName.equals("通过")) {
                state="1";
            }
        } else if (name.equals("事业部总经理审核")) {
            mm.setSybzjl(dbname);
            if (btnName.equals("通过")) {
                state="1";
            }
        } else if (name.equals("供应链金融产品经理审核")) {
            mm.setGyljrcpjl(dbname);
            if (btnName.equals("通过")) {
                state="1";
            }
        } else if (name.equals("供应链总经理审核")) {
            mm.setGylzjl(dbname);
        }

        variables.put("message", btnName);
        if (btnName.equals("通过") && name.equals("供应链总经理审核")) {
            variables.put("messages", "其他");

            state="2";
        }
        if (!"驳回".equals(btnName)) {
            variables.put("nextUser", dbUser);
        }
        if ("驳回".equals(btnName)) {
            variables.put("nextUser", dbUser);
            state="3";
        }
        mm.setAudit_state(state);
        mm.setId(id);
        int flag = copeCreditService.updatePass(mm,user.getId(),pocessId, variables, commons, id,
                user.getId(), btnName, dbUser,cl_time);
        Json json = new Json();
        if (flag > 0) {
            json.setFlag(true);
        } else {
            json.setFlag(false);
        }

        return json;
    }

    /**
     *  查询我的申请信息
     *
     */
    @RequestMapping("/getCreditInfo")
    public @ResponseBody List<CopeCredit> getCreditInfo(Integer state,Integer size,String token){
        List<CopeCredit>list=copeCreditService.creditList(state,size,token);
        return list;
    }


    /**
     * 查询单个申请详细信息
     * @param id
     * @return
     */
    @RequestMapping("/getsingCreditApplyInfo")
    public @ResponseBody Map<String,Object> getsingCreditApplyInfo(String id){
        CopeCredit list=copeCreditService.getsingCreditApplyInfo(id);
        List<Comment> comments=copeCreditService.getComment(list.getProcessId());
        List<CopeFile> mfList=copeCreditService.getImgS(id);
        Map<String,Object> map = new HashMap<String,Object>();

        map.put("mm", list);
        map.put("list", comments);
        map.put("mfList", mfList);
        return map;
    }

    @RequestMapping("/getLiuChengGuiJi")
    public @ResponseBody  List<CopeGuiJi> getLiuChengGuiJi(Integer state,Integer size,String proId) {
        List<CopeGuiJi> list=	copeCreditService.getLiuChengGuiJi(state,size,proId);

        return list;

    }

    @RequestMapping("/getGuiJi")
    public @ResponseBody List<CopeCredit> getGuiJi(Integer state,Integer size,String token) {

        List<CopeCredit> list = copeCreditService.guiJiList(state,size,token);
        return list;

    }

    @RequestMapping("/getsingGuiJi")
    public @ResponseBody CopeCredit getsingGuiJi(String id) {

        CopeCredit list = copeCreditService.getsingGuiJi(id);
        return list;

    }

    @RequestMapping(params = "method=getBh")
    public @ResponseBody String getBh(String name, HttpServletRequest request,HttpSession session) {
        User user = (User) session.getAttribute(SessionInfo.SessionName);
        List<CopeCredit> list = copeCreditService.getBh(name,user.getId());
        JSONObject jb = null;
        JSONArray jsons = new JSONArray();
        for (CopeCredit c : list) {
            jb = new JSONObject();
            jb.put("id", c.getBh());
            jb.put("name", c.getBh());
            jsons.add(jb);
        }
        return jsons.toString();

    }
    @RequestMapping(params = "method=getBh2")
    public @ResponseBody CopeCredit getBh2(String name, HttpServletRequest request) {
        CopeCredit c = copeCreditService.getBh2(name);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());//时间Data转换成String型
        MoneyManage mm4=copeCreditService.getBh4(name,date);
        double apply_money4=0;//实际还款1
        if(mm4!=null){

            apply_money4=Double.parseDouble(mm4.getApply_money());
        }
        MoneyManage mm5=copeCreditService.getBh5(name,date);
        double apply_money5=0;//实际还款2
        if(mm5!=null){

            apply_money5=Double.parseDouble(mm5.getApply_money());
        }
        MoneyManage mm6=copeCreditService.getBh6(name,date);

        double apply_money6=0;//未还款
        if(mm6!=null){

            apply_money6=Double.parseDouble(mm6.getApply_money());
            // System.out.println(apply_money6+"apply_money6=====");
        }

        double total_money=Double.parseDouble(c.getApply_money());
        double money=total_money-apply_money4-apply_money5-apply_money6;
        //System.out.println(c.getApply_money()+"=="+money+"-===-----");
        c.setApply_money(String.valueOf(money));
        return c;

    }

    /**
     * 撤销流程
     * @param id
     * @param process_id
     * @return
     */
    @RequestMapping("/iscx")
    public @ResponseBody Boolean  iscx(String id,String process_id,String realname,String userId){
        //User user=(User)session.getAttribute(SessionInfo.SessionName);
        int i=copeCreditService.iscx(id,process_id,realname,userId);
        if(i>0){
            return true;
        }else{
            return false;
        }
    }


    @RequestMapping("/applyTj")
    public @ResponseBody
    Json applySj(HttpSession session, String pocessId, String dbUser,
                 String dbname, String id, String type,String cl_time) {
        User user = (User) session.getAttribute(SessionInfo.SessionName);
        //System.out.println("取到流程ID啦：" + pocessId + "代办人也来了：" + dbUser);
        //System.out.println("id:" + id);

        Map<String, Object> variables = new HashMap<String, Object>();

        variables.put("message", "事业部");

        String dbnames = dbname.substring(0, dbname.indexOf("--"));
        MoneyManage mm = new MoneyManage();
        mm.setSybcwzj(dbnames);
        mm.setId(id);


        variables.put("nextUser", dbUser);

        boolean flag = copeCreditService.updateState(pocessId, variables, id, dbUser,
                dbUser,cl_time,user.getId());
        Json json = new Json();
        json.setFlag(flag);

        return json;
    }


    @RequestMapping("/searchApply")
    public @ResponseBody Json searchApply(HttpSession session, CopeCredit mm) {
        Json json = new Json();
        List<CopeCredit> list=copeCreditService.searchApply(mm);
        if(list.size()>0){
            json.setFlag(false);
        }else{
            json.setFlag(true);
        }
        return json;
    }
}
